<template>
  <div class="upstream-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>上游渠道管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleAdd">新增渠道</el-button>
            <el-button @click="handleExport">导出渠道</el-button>
            <el-button @click="handleImport">导入渠道</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="渠道名称">
          <el-input v-model="searchForm.channelName" placeholder="请输入渠道名称" clearable />
        </el-form-item>
        <el-form-item label="渠道类型">
          <el-select v-model="searchForm.channelType" placeholder="请选择渠道类型" clearable>
            <el-option label="银行" value="bank" />
            <el-option label="消费金融" value="consumer_finance" />
            <el-option label="小贷公司" value="small_loan" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="enabled" />
            <el-option label="禁用" value="disabled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 批量操作 -->
      <div class="batch-actions">
        <el-button 
          type="danger" 
          @click="handleBatchDelete"
          :disabled="selectedRows.length === 0"
        >
          批量删除
        </el-button>
        <el-button 
          @click="handleBatchStatus('enabled')"
          :disabled="selectedRows.length === 0"
        >
          批量启用
        </el-button>
        <el-button 
          @click="handleBatchStatus('disabled')"
          :disabled="selectedRows.length === 0"
        >
          批量禁用
        </el-button>
        <el-button 
          @click="handleBatchConfig"
          :disabled="selectedRows.length === 0"
        >
          批量配置
        </el-button>
      </div>

      <!-- 渠道表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="channelName" label="渠道名称" min-width="150" />
        <el-table-column prop="channelType" label="渠道类型" width="120">
          <template #default="{ row }">
            <el-tag>{{ getChannelTypeLabel(row.channelType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="apiEndpoint" label="API地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="dailyLimit" label="日限额" width="100" />
        <el-table-column prop="priority" label="优先级" width="80" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              active-value="enabled"
              inactive-value="disabled"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="successRate" label="成功率" width="80">
          <template #default="{ row }">
            <span :class="getSuccessRateClass(row.successRate)">
              {{ row.successRate }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click="handleView(row)">查看</el-button>
            <el-button type="text" @click="handleEdit(row)">编辑</el-button>
            <el-button type="text" @click="handleTest(row)">测试</el-button>
            <el-button type="text" @click="handleApiConfig(row)">API配置</el-button>
            <el-button type="text" @click="handleDelete(row)" style="color: #f56c6c">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
      />
    </el-card>

    <!-- 渠道详情对话框 -->
    <el-dialog
      v-model="detailDialog.visible"
      title="渠道详情"
      width="700px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="渠道名称">{{ detailDialog.data.channelName }}</el-descriptions-item>
        <el-descriptions-item label="渠道类型">
          <el-tag>{{ getChannelTypeLabel(detailDialog.data.channelType) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="API地址">{{ detailDialog.data.apiEndpoint }}</el-descriptions-item>
        <el-descriptions-item label="API密钥">{{ detailDialog.data.apiKey || '无' }}</el-descriptions-item>
        <el-descriptions-item label="日限额">{{ detailDialog.data.dailyLimit }}</el-descriptions-item>
        <el-descriptions-item label="优先级">{{ detailDialog.data.priority }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="detailDialog.data.status === 'enabled' ? 'success' : 'danger'">
            {{ detailDialog.data.status === 'enabled' ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="成功率">
          <span :class="getSuccessRateClass(detailDialog.data.successRate)">
            {{ detailDialog.data.successRate }}%
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="今日调用次数">{{ detailDialog.data.todayCalls }}</el-descriptions-item>
        <el-descriptions-item label="今日成功次数">{{ detailDialog.data.todaySuccess }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detailDialog.data.remark || '无' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailDialog.data.createdTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailDialog.data.updatedTime }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 新增/编辑渠道对话框 -->
    <el-dialog
      v-model="formDialog.visible"
      :title="formDialog.title"
      width="600px"
    >
      <el-form ref="channelFormRef" :model="formDialog.form" :rules="formRules" label-width="100px">
        <el-form-item label="渠道名称" prop="channelName">
          <el-input v-model="formDialog.form.channelName" placeholder="请输入渠道名称" />
        </el-form-item>
        <el-form-item label="渠道类型" prop="channelType">
          <el-select v-model="formDialog.form.channelType" placeholder="请选择渠道类型" style="width: 100%">
            <el-option label="银行" value="bank" />
            <el-option label="消费金融" value="consumer_finance" />
            <el-option label="小贷公司" value="small_loan" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="API地址" prop="apiEndpoint">
          <el-input v-model="formDialog.form.apiEndpoint" placeholder="请输入API地址" />
        </el-form-item>
        <el-form-item label="API密钥" prop="apiKey">
          <el-input v-model="formDialog.form.apiKey" placeholder="请输入API密钥" show-password />
        </el-form-item>
        <el-form-item label="日限额" prop="dailyLimit">
          <el-input-number 
            v-model="formDialog.form.dailyLimit" 
            :min="0" 
            :step="100"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-input-number 
            v-model="formDialog.form.priority" 
            :min="1" 
            :max="10"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formDialog.form.status">
            <el-radio label="enabled">启用</el-radio>
            <el-radio label="disabled">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formDialog.form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="formDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 批量配置对话框 -->
    <el-dialog
      v-model="batchConfigDialog.visible"
      title="批量配置"
      width="500px"
    >
      <el-form ref="batchConfigFormRef" :model="batchConfigDialog.form" label-width="100px">
        <el-form-item label="日限额">
          <el-input-number 
            v-model="batchConfigDialog.form.dailyLimit" 
            :min="0" 
            :step="100"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="优先级">
          <el-input-number 
            v-model="batchConfigDialog.form.priority" 
            :min="1" 
            :max="10"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="batchConfigDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleBatchConfigSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- API配置对话框 -->
    <el-dialog
      v-model="apiConfigDialog.visible"
      title="API配置"
      width="700px"
    >
      <el-form :model="apiConfigDialog.form" label-width="120px">
        <el-form-item label="请求头配置">
          <div class="header-config">
            <div v-for="(header, index) in apiConfigDialog.form.headers" :key="index" class="header-item">
              <el-input v-model="header.key" placeholder="Header Key" style="width: 200px; margin-right: 10px" />
              <el-input v-model="header.value" placeholder="Header Value" style="width: 200px; margin-right: 10px" />
              <el-button type="danger" size="small" @click="removeHeader(index)">删除</el-button>
            </div>
            <el-button type="primary" size="small" @click="addHeader" style="margin-top: 10px">添加请求头</el-button>
          </div>
        </el-form-item>
        <el-form-item label="请求超时时间(秒)">
          <el-input-number v-model="apiConfigDialog.form.timeout" :min="5" :max="300" style="width: 100%" />
        </el-form-item>
        <el-form-item label="重试次数">
          <el-input-number v-model="apiConfigDialog.form.retryCount" :min="0" :max="10" style="width: 100%" />
        </el-form-item>
        <el-form-item label="重试间隔(秒)">
          <el-input-number v-model="apiConfigDialog.form.retryInterval" :min="1" :max="60" style="width: 100%" />
        </el-form-item>
        <el-form-item label="响应格式">
          <el-radio-group v-model="apiConfigDialog.form.responseFormat">
            <el-radio label="json">JSON</el-radio>
            <el-radio label="xml">XML</el-radio>
            <el-radio label="form">Form</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="响应解析路径">
          <el-input v-model="apiConfigDialog.form.responsePath" placeholder="例如: data.result" />
        </el-form-item>
        <el-form-item label="状态字段名">
          <el-input v-model="apiConfigDialog.form.statusField" placeholder="例如: code" />
        </el-form-item>
        <el-form-item label="成功状态值">
          <el-input v-model="apiConfigDialog.form.statusSuccessValue" placeholder="例如: 200" />
        </el-form-item>
        <el-form-item label="消息字段名">
          <el-input v-model="apiConfigDialog.form.messageField" placeholder="例如: message" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="apiConfigDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleApiConfigSubmit">确定</el-button>
      </template>
    </el-dialog>
    </el-dialog>
   </template>
   
   <script setup lang="ts">
   import { ref, reactive, onMounted } from 'vue'
   import { ElMessage, ElMessageBox } from 'element-plus'
   import { getUpstreamChannels, createUpstreamChannel, updateUpstreamChannel, deleteUpstreamChannel, batchUpdateUpstreamChannel, exportUpstreamChannels, testUpstreamChannel, updateUpstreamChannelApiConfig } from '@/api/channel'
   
   // 表格数据
   const loading = ref(false)
   const tableData = ref([])
   const selectedRows = ref([])
   
   // 搜索表单
   const searchForm = reactive({
     channelName: '',
     channelType: '',
     status: ''
   })
   
   // 分页
   const pagination = reactive({
     currentPage: 1,
     pageSize: 10,
     total: 0
   })
   
   // 对话框状态
   const detailDialog = reactive({
     visible: false,
     data: {}
   })
   
   const formDialog = reactive({
     visible: false,
     title: '新增渠道',
     form: {
       channelName: '',
       channelType: '',
       apiEndpoint: '',
       apiKey: '',
       dailyLimit: 1000,
       priority: 5,
       status: 'enabled',
       remark: ''
     }
   })
   
   const batchConfigDialog = reactive({
     visible: false,
     form: {
       dailyLimit: 1000,
       priority: 5
     }
   })
   
   const apiConfigDialog = reactive({
     visible: false,
     channelId: null,
     form: {
       headers: [],
       timeout: 30,
       retryCount: 3,
       retryInterval: 5,
       responseFormat: 'json',
       responsePath: '',
       statusField: '',
       statusSuccessValue: '',
       messageField: ''
     }
   })
   
   // 表单验证规则
   const formRules = {
     channelName: [
       { required: true, message: '请输入渠道名称', trigger: 'blur' }
     ],
     channelType: [
       { required: true, message: '请选择渠道类型', trigger: 'change' }
     ],
     apiEndpoint: [
       { required: true, message: '请输入API地址', trigger: 'blur' },
       { type: 'url', message: '请输入有效的URL地址', trigger: 'blur' }
     ],
     dailyLimit: [
       { required: true, message: '请输入日限额', trigger: 'blur' }
     ],
     priority: [
       { required: true, message: '请输入优先级', trigger: 'blur' }
     ]
   }
   
   // 获取渠道类型标签
   const getChannelTypeLabel = (type: string) => {
     const labels = {
       bank: '银行',
       consumer_finance: '消费金融',
       small_loan: '小贷公司',
       other: '其他'
     }
     return labels[type] || type
   }
   
   // 获取成功率样式类
   const getSuccessRateClass = (rate: number) => {
     if (rate >= 90) return 'text-success'
     if (rate >= 70) return 'text-warning'
     return 'text-danger'
   }
   
   // 获取表格数据
   const fetchData = async () => {
     loading.value = true
     try {
       const params = {
         ...searchForm,
         page: pagination.currentPage,
         pageSize: pagination.pageSize
       }
       const { data } = await getUpstreamChannels(params)
       tableData.value = data.list
       pagination.total = data.total
     } catch (error) {
       ElMessage.error('获取数据失败')
     } finally {
       loading.value = false
     }
   }
   
   // 搜索
   const handleSearch = () => {
     pagination.currentPage = 1
     fetchData()
   }
   
   // 重置
   const handleReset = () => {
     Object.assign(searchForm, {
       channelName: '',
       channelType: '',
       status: ''
     })
     handleSearch()
   }
   
   // 分页
   const handleSizeChange = (val: number) => {
     pagination.pageSize = val
     fetchData()
   }
   
   const handleCurrentChange = (val: number) => {
     pagination.currentPage = val
     fetchData()
   }
   
   // 表格选择
   const handleSelectionChange = (val: any[]) => {
     selectedRows.value = val
   }
   
   // 查看详情
   const handleView = async (row: any) => {
     detailDialog.data = { ...row }
     detailDialog.visible = true
   }
   
   // 新增
   const handleAdd = () => {
     formDialog.title = '新增渠道'
     formDialog.form = {
       channelName: '',
       channelType: '',
       apiEndpoint: '',
       apiKey: '',
       dailyLimit: 1000,
       priority: 5,
       status: 'enabled',
       remark: ''
     }
     formDialog.visible = true
   }
   
   // 编辑
   const handleEdit = (row: any) => {
     formDialog.title = '编辑渠道'
     formDialog.form = { ...row }
     formDialog.visible = true
   }
   
   // 测试
   const handleTest = async (row: any) => {
     try {
       await testUpstreamChannel(row.id)
       ElMessage.success('测试连接成功')
     } catch (error) {
       ElMessage.error('测试连接失败')
     }
   }
   
   // 删除
   const handleDelete = async (row: any) => {
     try {
       await ElMessageBox.confirm('确定要删除该渠道吗？', '提示', {
         type: 'warning'
       })
       await deleteUpstreamChannel(row.id)
       ElMessage.success('删除成功')
       fetchData()
     } catch (error) {
       if (error !== 'cancel') {
         ElMessage.error('删除失败')
       }
     }
   }
   
   // 状态变更
   const handleStatusChange = async (row: any) => {
     try {
       await updateUpstreamChannel(row.id, { status: row.status })
       ElMessage.success('状态更新成功')
     } catch (error) {
       ElMessage.error('状态更新失败')
       // 恢复状态
       row.status = row.status === 'enabled' ? 'disabled' : 'enabled'
     }
   }
   
   // 提交表单
   const handleSubmit = async () => {
     try {
       const formRef = formDialog.title === '新增渠道' ? 'channelFormRef' : 'channelFormRef'
       await formRef.validate()
       
       if (formDialog.title === '新增渠道') {
         await createUpstreamChannel(formDialog.form)
         ElMessage.success('新增成功')
       } else {
         await updateUpstreamChannel(formDialog.form.id, formDialog.form)
         ElMessage.success('更新成功')
       }
       
       formDialog.visible = false
       fetchData()
     } catch (error) {
       ElMessage.error('保存失败')
     }
   }
   
   // 批量删除
   const handleBatchDelete = async () => {
     if (selectedRows.value.length === 0) {
       ElMessage.warning('请选择要删除的渠道')
       return
     }
     
     try {
       await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个渠道吗？`, '提示', {
         type: 'warning'
       })
       const ids = selectedRows.value.map(row => row.id)
       await batchUpdateUpstreamChannel({ ids, action: 'delete' })
       ElMessage.success('批量删除成功')
       fetchData()
     } catch (error) {
       if (error !== 'cancel') {
         ElMessage.error('批量删除失败')
       }
     }
   }
   
   // 批量状态更新
   const handleBatchStatus = async (status: string) => {
     if (selectedRows.value.length === 0) {
       ElMessage.warning('请选择要操作的渠道')
       return
     }
     
     try {
       const action = status === 'enabled' ? '启用' : '禁用'
       await ElMessageBox.confirm(`确定要${action}选中的 ${selectedRows.value.length} 个渠道吗？`, '提示', {
         type: 'warning'
       })
       const ids = selectedRows.value.map(row => row.id)
       await batchUpdateUpstreamChannel({ ids, action: 'status', status })
       ElMessage.success(`批量${action}成功`)
       fetchData()
     } catch (error) {
       if (error !== 'cancel') {
         ElMessage.error('批量操作失败')
       }
     }
   }
   
   // 批量配置
   const handleBatchConfig = () => {
     if (selectedRows.value.length === 0) {
       ElMessage.warning('请选择要配置的渠道')
       return
     }
     batchConfigDialog.visible = true
   }
   
   // 提交批量配置
   const handleBatchConfigSubmit = async () => {
     try {
       const ids = selectedRows.value.map(row => row.id)
       await batchUpdateUpstreamChannel({
         ids,
         action: 'config',
         ...batchConfigDialog.form
       })
       ElMessage.success('批量配置成功')
       batchConfigDialog.visible = false
       fetchData()
     } catch (error) {
       ElMessage.error('批量配置失败')
     }
   }
   
   // 导出
   const handleExport = async () => {
     try {
       const blob = await exportUpstreamChannels(searchForm)
       const url = window.URL.createObjectURL(blob)
       const link = document.createElement('a')
       link.href = url
       link.download = `上游渠道_${new Date().toLocaleDateString()}.xlsx`
       link.click()
       window.URL.revokeObjectURL(url)
       ElMessage.success('导出成功')
     } catch (error) {
       ElMessage.error('导出失败')
     }
   }
   
   // 导入
   const handleImport = () => {
     // TODO: 实现导入功能
     ElMessage.info('导入功能开发中')
   }
   
   // 添加请求头
   const addHeader = () => {
     apiConfigDialog.form.headers.push({ key: '', value: '' })
   }
   
   // 删除请求头
   const removeHeader = (index: number) => {
     apiConfigDialog.form.headers.splice(index, 1)
   }
   
   // 打开API配置对话框
   const handleApiConfig = (row: any) => {
     // 保存当前渠道ID
     apiConfigDialog.channelId = row.id
     // 初始化API配置表单数据
     apiConfigDialog.form = {
       headers: row.apiConfig?.headers || [],
       timeout: row.apiConfig?.timeout || 30,
       retryCount: row.apiConfig?.retryCount || 3,
       retryInterval: row.apiConfig?.retryInterval || 5,
       responseFormat: row.apiConfig?.responseFormat || 'json',
       responsePath: row.apiConfig?.responsePath || '',
       statusField: row.apiConfig?.statusField || '',
       statusSuccessValue: row.apiConfig?.statusSuccessValue || '',
       messageField: row.apiConfig?.messageField || ''
     }
     apiConfigDialog.visible = true
   }
   
   // 提交API配置
  const handleApiConfigSubmit = async () => {
    try {
      // 过滤空的请求头
      const validHeaders = apiConfigDialog.form.headers.filter(h => h.key && h.value)
      const configData = {
        ...apiConfigDialog.form,
        headers: validHeaders
      }
      
      // 使用保存的渠道ID
      if (!apiConfigDialog.channelId) {
        ElMessage.error('请先选择要配置API的渠道')
        return
      }
      
      await updateUpstreamChannelApiConfig(apiConfigDialog.channelId, configData)
      ElMessage.success('API配置保存成功')
      apiConfigDialog.visible = false
      fetchData()
    } catch (error) {
      ElMessage.error('API配置保存失败')
    }
  }
   
   // 初始化
   onMounted(() => {
     fetchData()
   })
   </script>
   
   <style scoped lang="scss">
   .upstream-management {
     .card-header {
       display: flex;
       justify-content: space-between;
       align-items: center;
     }
   
     .search-form {
       margin-bottom: 20px;
     }
   
     .batch-actions {
       margin-bottom: 20px;
     }
   
     .pagination {
       margin-top: 20px;
       display: flex;
       justify-content: flex-end;
     }
   
     .text-success {
       color: #67c23a;
     }
   
     .text-warning {
       color: #e6a23c;
     }
   
     .text-danger {
       color: #f56c6c;
     }
   }
   </style>